//
//  WmcWatermarkSelectCell.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/4/2.
//

import UIKit
import YPBedrock

// MARK: - [WmcWatermarkSelectCell]

class WmcWatermarkSelectCell: WmcBaseCollectionCell {
    let inset: UIEdgeInsets = Wmc_standardEdge.yp.set(top:8).yp.set(bottom:Wmc_safeAreaBottom + 8)
    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout
            .YP.CreateGridLayout(scrollDirection: .vertical,
                                 minimumLineSpacing: 0,
                                 minimumInteritemSpacing: 8,
                                 sectionInset: inset)
        return layout
    }()

    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView
            .YP.Create(layout: layout,
                       delegate: self,
                       dataSource: self,
                       registers: [
                           YPRegister(WmcWatermarkCell.self),
                           YPRegister(WmcWatermarkSelectFooterView.self, style: .footer),
                       ])

        return collectionView
    }()

    /// 组
    var section: Int = 0
    /// 分类模型
    var model: WmcWatermarkClassifyModel?
    /// 选中
    var selectArray: [Bool] = []
    /// 点击回调
    var didSelectWatermarkBlock: YPBlock.TwoParam<IndexPath, WmcWatermarkDetailModel>?
    /// 是否被重新加载
    var isLoadRest: Bool = false
    /// 消失回调
    var dismissBlock: YPBlock.Empty?

    var shareBlock: YPBlock.OneParam<WmcWatermarkDetailModel>?
    var editBlock: YPBlock.OneParam<WmcWatermarkDetailModel>?

    override func makeUI() {
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    func willDisplay() {
        isLoadRest = true
    }

    func configModel(_ model: WmcWatermarkClassifyModel, rowSelectArray: [Bool]) {
        self.model = model
        self.selectArray = rowSelectArray
        var selectIdx: Int?
        for (idx, bol) in selectArray.enumerated() {
            if bol {
                selectIdx = idx
            }
        }
        collectionView.reloadData()
        if let selectIdx = selectIdx, // 有选中的
           model.watermarks.count > selectIdx
        {
            collectionView.layoutIfNeeded()
            collectionView.scrollToItem(at: .init(row: selectIdx, section: 0),
                                        at: .centeredVertically,
                                        animated: false) // 避免首次滑动跳跃的问题
        }
    }
}

// MARK: - UICollectionViewDelegate

extension WmcWatermarkSelectCell: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let model = model?.watermarks.yp.object(at: indexPath.row) {
            isLoadRest = false
            didSelectWatermarkBlock?(.init(row: indexPath.row, section: section), model)
        }
    }
}

// MARK: - UICollectionViewDelegateFlowLayout

extension WmcWatermarkSelectCell: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: collectionView.frame.width, height: 35)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let lineCount: CGFloat = 2
        let lineSpacing = self.layout.minimumInteritemSpacing * (lineCount - 1)
        let horizontalEdge = self.layout.sectionInset.yp.horizontal
        let width = (collectionView.frame.size.width - lineSpacing - horizontalEdge) / lineCount - 1
        let height = width * 0.872
        return CGSize(width: width, height: height)
    }
}

// MARK: - UICollectionViewDataSource

extension WmcWatermarkSelectCell: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionFooter {
            let footerView: WmcWatermarkSelectFooterView = collectionView.yp.dequeueReusableView(.init(WmcWatermarkSelectFooterView.self,
                                                                                                       style: .footer),
                                                                                                 indexPath: indexPath)
            footerView.promptBtn.yp.addEvent { [weak self] _ in
                guard let weakSelf = self else { return }
                weakSelf.dismissBlock?()
                YPApp.CurrentVC?.dismiss(animated: true, completion: {
                    // 调用优化之后的h5页面
                    if let currentVC = YPApp.CurrentVC as? WmcHomeVC {
                        currentVC.stopCamera()
                        let vm = WmcHtml5VM()
                        vm.parameters = nil
                        vm.questionType = .WatermarkType
                        vm.path = WmcHtml5VM.Html5Path.feedback
                        WmcNavigatorManager.push(.html5Page, parms: vm)
                    }
                    
                    if let _ = YPApp.CurrentVC as? WmcPhotoPreviewVC {
                        let vm = WmcHtml5VM()
                        vm.parameters = nil
                        vm.questionType = .WatermarkType
                        vm.path = WmcHtml5VM.Html5Path.feedback
                        WmcNavigatorManager.push(.html5Page, parms: vm)
                    }
                })
            }
            return footerView
        } else {
            return .init()
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return model?.watermarks.count ?? 0
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: WmcWatermarkCell = collectionView.yp.dequeueReusableCell(for: indexPath)
        if let model = model?.watermarks.yp.object(at: indexPath.row),
           let isSelect = selectArray.yp.object(at: indexPath.row)
        {
            cell.shareBlock = shareBlock
            cell.editBlock = editBlock
            cell.configModel(model, isSelect: isSelect)
        }
        return cell
    }
}
